package org.veloxbot.api.internals.randoms;

import org.veloxbot.api.internals.Context;

import org.veloxbot.api.internals.concurrent.Task;
import org.veloxbot.api.internals.concurrent.LoopTask;
import org.veloxbot.api.internals.concurrent.TaskExecutor;

import org.veloxbot.api.utils.Random;

import java.util.List;
import java.util.ArrayList;

/**
 * @author Velox
 */
public class RandomHandler extends LoopTask {

	/**
	 * Whether the random handler is solving an event or not.
	 */
	public static boolean solving = false;

	/**
	 * A list of submitted random events.
	 */
	public static List<RandomEvent> randoms = new ArrayList<RandomEvent>();

	public RandomHandler() {
		TaskExecutor.submit(this);
	}

	/**
	 * What to do when the random event is executed.
	 *
	 * @return The amount of time to sleep.
	 */
	@Override
	public final int loop() {
		for (final RandomEvent event : randoms) {
			if (event.validate()) {
				solving = true;
				Context.script.setPause(true);
				while (event.validate()) {
					final int loop = event.loop();
					if (loop > 0) {
						Task.sleep(loop);
					} else {
						break;
					}
				}
				Context.script.setPause(false);
				solving = false;
			}
			Task.sleep(5, 10);
		}
		return Random.nextInt(50, 100);
	}
}
